from flask import abort, jsonify
from flask import current_app
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for

from info import db
from info.constants import USER_COLLECTION_MAX_NEWS, QINIU_DOMIN_PREFIX
from info.models import tb_user_collection, News, Category
from info.utils.common import user_login_data, file_upload
from info.utils.response_code import RET, error_map
from . import user_blu


# 个人中心
@user_blu.route('/user_info')
@user_login_data  # 取出用户数据
def user_info():
    # 判断用户是否登录
    user = g.user
    if not user:  # 未登录
        return redirect(url_for("home.index"))

    # 后端模板渲染
    return render_template("new/user.html", user=user.to_dict())


# 基本设置
@user_blu.route('/base_info', methods=['GET', 'POST'])
@user_login_data
def base_info():
    # 判断用户是否登录
    user = g.user
    if not user:
        return abort(403)

    # GET 展示数据
    if request.method == 'GET':
        return render_template("new/user_base_info.html", user=user.to_dict())

    # post提交数据
    # 获取数据  signature    nick_name  gender
    signature = request.json.get("signature")
    nick_name = request.json.get("nick_name")
    gender = request.json.get("gender")

    # 校验参数all
    if not all([signature, nick_name, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 校验gender  man ,woman
    if gender not in ["MAN", "WOMAN"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 更改数据库数据
    user.signature = signature
    user.nick_name = nick_name
    user.gender = gender

    # 返回json
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


# 头像设置
@user_blu.route('/pic_info', methods=['GET', 'POST'])
@user_login_data
def pic_info():
    # 判断用户是否登录
    user = g.user
    if not user:
        return abort(403)

    # GET展示数据 返回页面及用户数据
    if request.method == "GET":
        return render_template('new/user_pic_info.html', user=user.to_dict())

    # 获取文件
    img_file = request.files.get("avatar")

    # 读取文件二进制
    try:
        img_bytes = img_file.read()
        # print(img_bytes)

    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    # 保存到第三方服务器
    try:
        file_name = file_upload(img_bytes)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg=error_map[RET.THIRDERR])
    # 记录保存文件名
    user.avatar_url = file_name
    # print( user.avatar_url)
    # 返回json 及 新的文件路径
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=user.to_dict())


# 修改密码
@user_blu.route('/pass_info', methods=['GET', 'POST'])
@user_login_data
def pass_info():
    # 判断用户是否登录
    user = g.user
    if not user:
        return abort(403)

    # GET 返回静态文件
    if request.method == "GET":
        return current_app.send_static_file("news/html/user_pass_info.html")

    # 获取数据  old_password  new_password
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")
    # 校验参数all
    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    # 校验old_password 是否正确
    if not user.check_password(old_password):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    # 保存新密码
    user.password = new_password

    # 返回json ok
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


# 显示收藏
@user_blu.route('/collection')
@user_login_data
def collection():
    # 判断用户是否登录
    user = g.user
    if not user:
        return abort(403)
    # 获取参数
    p = request.args.get("p", 1)
    # 校验参数
    try:
        p = int(p)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(403)

    # 查询数据 用户所有的收藏新闻 倒序
    try:
        pn = user.collection_news.order_by(tb_user_collection.c.create_time.desc()).paginate(p,
                                                                                             USER_COLLECTION_MAX_NEWS)
    except BaseException as e:
        current_app.logger(e)

    # 返回HTML 当前页码  总页码
    data = {
        "news_list": [news.to_dict() for news in pn.items],
        "cur_page": pn.page,
        "total_page": pn.pages
    }
    return render_template("new/user_collection.html", data=data)


# 显示发布页面
@user_blu.route('/news_release', methods=['GET', 'POST'])
@user_login_data
def news_release():
    # 判断用户是否登录
    user = g.user
    if not user:
        return abort(403)
    if request.method == "GET":
        # 查询所有的分类数据
        try:
            categories = Category.query.all()
        except BaseException as e:
            current_app.logger.error(e)
            return abort(500)

        if len(categories):
            categories.pop(0)  # 删除"最新"数据

        return render_template("new/user_news_release.html", categories=categories)

    # 获取数据 title category digest index_image content
    # starus source index_image_url
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    content = request.form.get("content")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")

    # 校验参数
    if not all([title, category_id, digest, content, index_image]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 生成新闻模型
    news = News()
    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.content = content
    try:
        img_bytes = index_image.read()
        file_name = file_upload(img_bytes)
        news.index_image_url = QINIU_DOMIN_PREFIX + file_name
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 设置其他属性

    news.source = "个人发布"
    news.user_id = user.id
    news.status = 1

    db.session.add(news)
    # 返回josn
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


# 显示发布列表

@user_blu.route('/news_list')
@user_login_data
def news_list():
    # 判断用户是否登录
    user = g.user
    if not user:
        return abort(403)

    # 获取参数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(403)
    news_list = []
    try:
        pn = user.news_list.order_by(News.create_time.desc()).paginate(p, USER_COLLECTION_MAX_NEWS)
    except BaseException as e:
        current_app.logger.error(e)
    data = {
        "news_list": [news.to_review_dict() for news in pn.items],
        "cur_page": pn.page,
        "total_page": pn.pages
    }

    return render_template("new/user_news_list.html", data=data)


# 我的关注
@user_blu.route('/user_follow')
@user_login_data
def user_follow():
    user = g.user
    if not user:
        return abort(403)
    # 获取参数
    p = request.args.get("p", 1)

    # 校验参数
    try:
        p = int(p)
    except BaseException as e:
        current_app.logger.error(e)

    # 查询当页关注
    try:
        pn = user.followed.paginate(p, USER_COLLECTION_MAX_NEWS)
    except BaseException as e:
        current_app.logger.error(e)

    data = {
        "author_lost": [user.to_dict() for user in pn.items],
        "cur_page":  pn.page,
        "total_page": pn.pages
    }
    return render_template("new/user_follow.html", data =data)
